package com.xsp.mybatisxmlsqlparser.config;

import com.xsp.mybatisxmlsqlparser.multidatabase.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@Slf4j
public class DbCharacteristicsConfig {

    private final DataSource dataSource;
    @Value("${spring.datasource.default-schema:}")
    private String defaultSchema;

    public DbCharacteristicsConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    public DbCharacteristics dbCharacteristics() throws SQLException {
        String databaseType = dataSource.getConnection().getMetaData().getDatabaseProductName();
        log.info("当前系统启用的数据库为: {}", databaseType);
        return switch (databaseType) {
            case "dm" -> new DmDbCharacteristics();
            case "kingbase" -> new KingbaseDbCharacteristics();
            case "MySQL" -> new MySqlDbCharacteristics();
            case "oracle" -> new OracleDbCharacteristics();
            case "PostgreSQL" -> new PostgreSqlDbCharacteristics(defaultSchema);
            default -> throw new IllegalArgumentException("Unknown database type: " + databaseType);
        };
    }
}
